// Created by wangliang on 2025/4/17.

import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';

import '../utils/logger.dart';

class HiveHelper {
  HiveHelper._();

  static final HiveHelper _instance = HiveHelper._();

  static HiveHelper get instance => _instance;
  bool _inited = false;
  Future init() async {
    if (_inited) {
      return;
    }
    final dir = await getApplicationDocumentsDirectory();
    Hive.init(dir.path);
    _inited = true;
  }
}

class ProxyHiveHelper {
  ProxyHiveHelper._();

  static final ProxyHiveHelper _instance = ProxyHiveHelper._();

  static ProxyHiveHelper get instance => _instance;

  static const String proxyBoxName = "proxy_box_name";

  bool? _proxyEnabled;
  bool? get proxyEnabled => _proxyEnabled;
  String? _proxyIp;
  String? get proxyIp => _proxyIp;

  init() async {
    try {
      Box box = await Hive.openBox(proxyBoxName);
      _proxyEnabled = box.get('proxy_enabled', defaultValue: false);
      _proxyIp = box.get('proxy_ip', defaultValue: '');
      await box.close();
    } catch (e) {
      Log.d('ProxyHiveHelper init failed $e');
    }
  }

  Future<void> setProxy(bool enabled, String ip) async {
    Box box = await Hive.openBox(proxyBoxName);
    await box.put('proxy_enabled', enabled);
    await box.put('proxy_ip', ip);
    await box.close();
    _proxyEnabled = enabled;
    _proxyIp = ip;
  }
}

class VersionCheckHiveHelper {
  VersionCheckHiveHelper._();

  static final VersionCheckHiveHelper _instance = VersionCheckHiveHelper._();

  static VersionCheckHiveHelper get instance => _instance;

  static const String _boxName = "version_check_box_name";

  // 版本对话框弹出的版本，非强升只弹出一次
  String _showAppVersion = '';
  init() async {
    try {
      Box box = await Hive.openBox(_boxName);
      _showAppVersion = box.get('show_version', defaultValue: '');
      await box.close();
    } catch (e) {
      Log.d('VersionCheckHiveHelper init failed $e');
    }
  }

  Future setShowAppVersion(String version) async {
    Box box = await Hive.openBox(_boxName);
    await box.put('show_version', version);
    await box.close();
    _showAppVersion = version;
  }

  bool shouldShowAppVersion(String version) => version != _showAppVersion;
}
